<?php
class Notification extends AppModel {
	public $name = 'Notification';
	public $tablePrefix = 'cakeforum_';

	public $belongsTo = array('User');

	public function addNotification($thread_id){
		/* Subscribe users to a thread */
		$this->create();
		$this->set('thread_id', $thread_id);
		$this->set('user_id', AuthComponent::User('id'));
		$this->set('token', String::uuid());
		if($this->save()){
			return true;
		}
		return false;
	}

	public function sendAll($parentData = null, $newThreadId = null){
		/* Send emails to all users subscribed to the thread $parentData['Thread']['id'] */
		foreach($this->find('all', array('conditions' => array('thread_id' => $parentData['Thread']['id']))) as $notification){
			if(AuthComponent::User('id') !== $notification['User']['id']){
				$email = new CakeEmail();
				$email->config('noreply');
				$email->template('thread_notification');
				$email->viewVars(array(
					'threadData' => $parentData,
					'userId' => $notification['User']['id'],
					'token' => $notification['Notification']['token'],
					'author' => AuthComponent::User('username'),
					'threadId' => $newThreadId,
					'parentThreadId' => $parentData['Thread']['id'],
					'threadTitle' => Inflector::slug($parentData['Thread']['title'], '-')
				));
				$email->to($notification['User']['email']);
				$email->subject('Reply to thread ' . $parentData['Thread']['title']);
				$email->emailFormat('html');

				$email->send();
				$email->reset();
			}

		}

	}

	public function isSubscribed($subscribedUsers){
		foreach($subscribedUsers as $user){
			if($user['User']['id'] == AuthComponent::User('id')){
				return $user['Notification']['token'];
			}
		}
		return null;
	}

	public function whoIsSubscribed($threadId = null){
		$this->recursive = -1;
		$options = array(
			'fields' => array('Notification.token', 'User.username', 'User.id'),
			'conditions' => array('Notification.thread_id' => $threadId),
			'joins' => array(
				array('table' => $this->tablePrefix . 'users',
					'alias' => 'User',
					'type' => 'LEFT',
					'conditions' => array(
						'User.id = Notification.user_id'
		))));
		return $this->find('all', $options);

	}
}